<template>
  <div
    class="zl-sign-agreement"
    v-if="show"
    style="width: 100%;box-sizing: border-box;"
    :style="extraStyle"
  >
    <div class="pdf-review" v-show="!showSignDialog">
      <div class="pdf-title">
        {{ agreementTitle }}
      </div>
      <div class="pdf-box">
        <div class="read-pdf"></div>
        <!-- <template v-if="pdfUrl && numPages">
          <vue-pdf
            v-for="i in numPages"
            :src="pdfUrl"
            :key="i"
            :page="i"
            style="display: inline-block; width: 100%"
          ></vue-pdf>
        </template> -->
      </div>
      <div class="sign-btn-box">
        <button
          class="sign-btn"
          @click="openSignDialog()"
          :style="signBtnStyle"
          :disabled="signBtnDisable"
        >
          我已知晓,立即签署
          <span v-if="countDown">({{ countDown }})</span>
        </button>
      </div>
    </div>
    <div v-if="showSignDialog" class="sign-background">
      <div class="sign-background-body">
        <div class="esign-title flex-center-wrap">
          <!-- <img
            class="esign-title-img"
            src="//image.zlketang.com/public/news/images/product_purchase/news_sign_back_left_x2.png"
          /> -->
          <div class="esign-title-img" @click="showSignDialog = false">
            <img
              style="width: 100%;
                  height: 100%;"
              src="http://image.zlketang.com/public/zl_wxpub/img/sign_agreement_left.png"
            />
          </div>

          <div class="esign-title-name">{{ agreementTitle }}</div>
          <div @click="showSignDialog = false" class="esign-title-back">
            返回
          </div>
        </div>
        <div class="name-sign">姓名签署:</div>
        <div class="esign-box">
          <vue-esign
            class="esignature"
            ref="esign"
            :width="722"
            :height="360"
            :isCrop="isCrop"
            :lineWidth="lineWidth"
            :lineColor="lineColor"
            :bgColor.sync="bgColor"
          />
        </div>
        <div class="user-id-box">
          身份证：
        </div>
        <div>
          <el-input
            v-model="userId"
            placeholder="请输入身份证"
            style="width:300px;border:none"
            clearable
          ></el-input>
        </div>
        <div class="sign-note">
          同学您好，为了保证您的协议权益，请您核对好自己的真实姓名并填写签署，一旦提交无法修改。
        </div>
        <div class="esigh-btns">
          <button
            @click="handleGenerate"
            class="sign-btn2 sign-btn-confirm fl"
            :disabled="signConfirmDisable"
          >
            确认无误并提交
          </button>
          <button @click="handleReset" class="sign-btn2 sign-btn-clean fl">
            清除
          </button>
        </div>
      </div>
    </div>
    <el-dialog
      class="confirm-sign-dialog"
      width="400px"
      :visible.sync="showAgreementConfirm"
    >
      <div class="confirm-sign-dialog-box">
        <div style="padding-bottom:20px">
          <div class="h13"></div>
          <div class="flex-wrap flex-center-wrap">
            <zl-icon icon="icon-tishi" :icon-style="allStyle"></zl-icon>
            <div class="dialog-content-title">
              确认提交签署？
            </div>
          </div>
        </div>
        <div class="dialog-content-footer flex-wrap flex-justify-end">
          <button
            class="dialog-btn cancel-btn"
            @click="showAgreementConfirm = false"
          >
            取消
          </button>
          <button class="dialog-btn confirm-btn" @click="signAgreementDone">
            确认
          </button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      class="confirm-sign-dialog"
      width="400px"
      :visible.sync="showAgreementWarning"
    >
      <div class="confirm-sign-dialog-box">
        <div class="close-dialog">
          <i class="el-icon-close" @click="showAgreementWarning = false"></i>
        </div>
        <div style="padding-bottom:42px">
          <div class="h13"></div>
          <div class="flex-wrap flex-center-wrap">
            <zl-icon icon="icon-tishi" :icon-style="allStyle"></zl-icon>
            <div class="dialog-content-title">
              您还未填写您的姓名
            </div>
          </div>
        </div>
        <div class="dialog-content-footer flex-wrap flex-justify-end">
          <button class="dialog-btn cancel-btn" @click="closeDialog">
            下次再说
          </button>
          <button
            class="dialog-btn confirm-btn"
            @click="showAgreementWarning = false"
          >
            去填写
          </button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { signAgreementResult, uploadImg } from '../../src/api/personal_center'
import VueSign from './vueSign.vue'
// import vuePdf from 'vue-pdf'
import zlIcon from '@/components/zlIcon.vue'

export default {
  name: 'zlSignAgreement',
  components: {
    'vue-esign': VueSign,
    // vuePdf,
    zlIcon
  },
  props: {
    extraStyle: {
      type: Object,
      default: () => ({})
    },
    show: {
      type: Boolean,
      default: false
    },
    pdfUrl: {
      type: String,
      default: ''
    },
    productId: {
      type: String,
      default: ''
    },
    tradeNo: {
      type: String,
      default: ''
    },
    agreementTitle: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      allStyle: {
        width: '18px',
        height: '18px',
        color: '#FFA347',
        marginRight: '10px',
        marginTop: '2px'
      },
      lineWidth: 6,
      lineColor: '#9FA6B3',
      bgColor: '',
      isCrop: false,
      // 签名生成图片
      resultImg: '',
      // 控制签名区域的展示
      showSignDialog: false,
      // 签署按钮样式
      signBtnStyle: {
        background: '#F0F1F2',
        color: '#9FA6B3'
      },
      // 签署按钮禁用
      signBtnDisable: true,
      // 5秒倒计时
      countDown: 5,
      // pdf页数
      numPages: 0,
      //用户身份证
      userId: '',
      //确认禁用
      signConfirmDisable: false,
      //提交的数据
      confirmData: {},
      //确认弹窗
      showAgreementConfirm: false,
      //未签名提示框
      showAgreementWarning: false
    }
  },
  methods: {
    //通知父组件关闭弹窗，刷新页面
    closeDialog() {
      this.$emit('update:show', false)
      this.$emit('signed')
    },
    // 显示签名区域
    openSignDialog() {
      this.showSignDialog = true
    },
    //Base64转图片
    dataURLtoFile(dataurl, filename = 'file') {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    handleReset() {
      this.$refs.esign.reset()
    },
    // 将签名生成图片，上传给后端
    handleGenerate() {
      let isMatch = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      let isMatchHongKong = /^[A-Z]{1,2}[0-9]{6,10}[0-9A-Z]$/
      let isMatchAoMen = /^[1|5|7][0-9]{6}[0-9A-Z]$/
      let isMatchTaiWan = /^[a-zA-Z][0-9]{9}$/
      if (
        !(
          isMatch.test(this.userId) ||
          isMatchHongKong.test(this.userId) ||
          isMatchAoMen.test(this.userId) ||
          isMatchTaiWan.test(this.userId)
        )
      ) {
        this.$message.warning('您的身份证号码格式有误，请检查~')
        return
      }
      this.$refs.esign
        .generate()
        .then(res => {
          //改图片格式，从64位改为链接
          this.resultImg = res
          let imgFile = this.dataURLtoFile(this.resultImg)
          if (imgFile) {
            let imgObj = new FormData()
            imgObj.append('type', 'refund_agreement_sign')
            imgObj.append('from', 'web')
            imgObj.append('images', imgFile)
            this.ajaxUpload('/wxpub/solution/upload_img', imgObj).then(rs => {
              this.confirmData = {
                product_id: this.productId,
                image: rs.img_path,
                trade_no: this.tradeNo,
                id_card: this.userId
              }
              this.showAgreementConfirm = true
            })
          }
        })
        .catch(err => {
          this.signConfirmDisable = true
          this.showAgreementWarning = true
          setTimeout(() => {
            this.signConfirmDisable = false
          }, 1000)
        })
      //上传图片所需参数
    },
    //完成签名调取接口，关闭弹窗
    signAgreementDone() {
      // 通知父组件关闭签协议组件
      // this.closeDialog()
      signAgreementResult(this.confirmData)
        .then(res => {
          this.showSignDialog = false
          this.countDown = 5
          // 通知父组件关闭签协议组件
          this.$message.success('签署完成！')
          this.closeDialog()
        })
        .catch(e => {
          this.$message.warning('签订失败！')
        })
    },
    //加载pdf
    addPdf() {
      let that = this
      this.$nextTick(() => {
        this.pdfH5 = new Pdfh5('.read-pdf', {
          pdfurl: this.pdfUrl,
          scrollEnable: true, // 是否允许pdf滚动1111111111
          zoomEnable: true // 是否允许pdf手势缩放111111111111
          // limit: 10
        })
        this.pdfH5.on('complete', function(status, msg, time) {
          let canvassImgList = document.getElementsByClassName('pageContainer')
          canvassImgList = Array.from(canvassImgList)
          canvassImgList.forEach(item => {
            item.getElementsByTagName('img')[0].style.width = '100%'
            this.isShowLoading = false
          })
          that.isShowLoading = false
          that.setTimer()
        })
      })
    },
    // 添加倒计时
    setTimer() {
      this.signBtnStyle = {
        background: '#F0F1F2',
        color: '#9FA6B3'
      }
      let a = setInterval(() => {
        this.countDown--
        if (this.countDown === 0) {
          clearInterval(a)
          this.signBtnDisable = false
          this.signBtnStyle = {
            background: '#3480FF',
            color: '#FFFFFF'
          }
        }
      }, 1000)
    }
  },
  watch: {
    pdfUrl: {
      immediate: true,
      handler(newVal, oldVal) {
        if (typeof window === 'object' && newVal) {
          this.addPdf()
        }
      }
    }
  },
  mounted() {}
}
</script>
<style scoped>
.esign {
  max-width: 1000px;
  margin: auto;
  padding: 10px;
}

.esigh-btns {
  width: 772px;
  height: 40px;
}
.sign-btn {
  width: 226px !important;
  height: 40px !important;
  border-radius: 20px !important;
  padding: 0 !important;
  cursor: pointer;
  border: none;
  background: #f0f1f2;
  color: #9fa6b3;
}
.sign-btn2 {
  width: 158px !important;
  height: 40px !important;
  border-radius: 20px !important;
  padding: 0 !important;
  cursor: pointer;
  border: none;
  color: #9fa6b3;
}
.sign-btn-clean {
  margin-left: 20px !important;
  border: 1px solid #9fa6b3 !important;
  font-size: 14px;
  font-weight: 500;
  color: #8c8c8c;
  line-height: 16px;
  box-sizing: border-box;
}
.sign-btn-confirm {
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  line-height: 16px;
  background: #3480ff;
}
.esigh-result {
  /* css-ignore */
  margin-top: 10px;
  box-sizing: border-box;
}
.esignature {
  margin: 0px 0;
  border-radius: 8px;
  background-color: #f7f9fc !important;
}
.viewerContainer::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
}
.zl-sign-agreement /deep/ .viewerContainer {
  height: 100%;
  width: 100%;
}

.esign-box {
  width: 772px;
  box-sizing: border-box;
}
.sign-background {
  width: 100%;
  background-color: rgb(255, 255, 255);
}
.sign-background-body {
  width: 800px;
  margin: 0 auto;
}
.pdf-review {
  width: 100%;
  height: 100%;
  z-index: 1001;
  background-color: rgb(255, 255, 255);
}
.pdf-box {
  width: 100%;
  height: 460px;
  box-sizing: border-box;
  margin: auto;
  margin-top: 23px;
  overflow-y: auto;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}
.pdf-back {
  /* css-ignore */
  font-weight: 400;
  width: 800px;
  margin: auto;
  margin-top: 16px;
  margin-bottom: 16px;
  height: 16px;
  font-size: 14px;
  font-weight: 400;
  color: #999;
  line-height: 16px;
  cursor: pointer;
}
.pdf-title {
  box-sizing: border-box;
  font-size: 20px;
  font-weight: 400;
  width: 800px;
  color: #262626;
  line-height: 27px;
}

.read-pdf {
  width: auto;
  height: 100%;
  z-index: 1000;
  overflow: auto;
  border: 1px solid #f0f0f0;
  box-sizing: border-box;
  border-radius: 8px;
}
.read-pdf img {
  width: 800px;
  height: auto;
}

.pageContainer {
  /* css-ignore */
  margin: auto;
  /* border: 1px solid #F0F0F0 ; */
}
.zl-sign-agreement /deep/ .pageNum {
  display: none !important;
}
.sign-btn-box {
  width: 226px;
  box-sizing: border-box;
  padding-top: 16px;
  margin: 0 auto;
}
.sign-note {
  height: 28px;
  font-size: 14px;
  color: #9fa6b3;
  line-height: 21px;
  margin-top: 24px;
  margin-bottom: 30px;
}
.sign-dialog-close {
  /* css-ignore */
  font-size: 18px;
  font-weight: bolder;
  width: 20px;
  height: 20px;
  position: absolute;
  top: 18px;
  right: 12px;
  line-height: 16px;
  color: #979797;
}
.user-id-box {
  height: 22px;
  font-size: 16px;
  font-weight: 400;
  color: #1a2840;
  line-height: 22px;
  margin-top: 30px;
  margin-bottom: 10px;
}

.zl-sign-agreement /deep/ .el-input__inner {
  background-color: #f7f9fc;
  border-radius: 8px;
  border: none;
}
.confirm-sign-dialog {
  margin-top: 20vh;
  /* position: relative; */
}
.zl-sign-agreement /deep/ .el-dialog {
  height: 125px !important;
}
.zl-sign-agreement /deep/ .el-dialog__body {
  padding: 0 20px 20px 20px;
}
.dialog-content-footer {
  height: 34px;
  width: 100%;
}
.dialog-btn {
  width: 86px;
  height: 32px;
  border-radius: 16px;
  line-height: 32px;
  font-size: 14px;
  font-weight: 400;
  cursor: pointer;
}
.dialog-content-title {
  height: 22px;
  font-size: 16px;
  font-weight: 500;
  color: #1a2840;
  line-height: 22px;
}
.cancel-btn {
  border: 1px solid #f0f1f2;
  color: #667080;
  margin-right: 15px;
}
.confirm-btn {
  background: #3480ff;
  color: #ffffff;
}
.h13 {
  height: 13px;
}
.confirm-sign-dialog >>> .el-dialog {
  height: 136px !important;
}
.confirm-sign-dialog-box {
  position: relative;
}
.close-dialog {
  position: absolute;
  top: 8px;
  right: -4px;
  font-size: 12px;
  color: #1d1d1d;
  cursor: pointer;
}
.name-sign {
  font-size: 16px;
  font-weight: 400;
  color: #1a2840;
  line-height: 22px;
  margin-bottom: 10px;
  margin-top: 30px;
}
.esign-title {
  position: relative;
}
.esign-title-name {
  display: inline-block;
  font-size: 20px;
  color: #1a2840;
  line-height: 28px;
  margin-left: 7px;
  font-weight: 400;
}
.esign-title-back {
  display: inline-block;
  width: 68px;
  height: 34px;
  border-radius: 17px;
  border: 1px solid #9fa6b3;
  text-align: center;
  line-height: 34px;
  font-size: 14px;
  color: #667080;
  position: absolute;
  top: 0;
  right: -20px;
  cursor: pointer;
}
.esign-title-img {
  width: 16px;
  height: 16px;
  cursor: pointer;
}
</style>
